package com.uairobot.bill.tomcat;

import java.io.File;

import javax.servlet.ServletException;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;

public class TomcatServer {
  public static Tomcat tomcat = null;

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    File webappsFile = TomcatUtil.getWebappsFile();
    File[] listFiles = webappsFile.listFiles();

    // 创建root目录
    String rootPath = webappsFile.getAbsoluteFile() + File.separator + "ROOT";
    File rootFile = new File(rootPath);
    if (!rootFile.exists()) {
      rootFile.mkdirs();
    }
    tomcat = new Tomcat();
    // 添加webapp
    try {
      tomcat.addWebapp("/", rootPath);
      System.out.println("add webapp " + "/" + "=>" + rootPath);
      for (File file : listFiles) {
        String contextPath = "/" + file.getName();
        String baseDir = file.getAbsolutePath();
        tomcat.addWebapp(contextPath, baseDir);
        System.out.println("add webapp " + contextPath + "=>" + baseDir);
      }
    } catch (ServletException e1) {
      e1.printStackTrace();
    }

    // 设置tomcat端口
    tomcat.setPort(TomcatUtil.getPort());
    // 启动tomcat
    try {
      tomcat.start();
    } catch (LifecycleException e) {
      e.printStackTrace();
    }
    long end = System.currentTimeMillis();
    System.out.println("启动完成,共使用了:" + (end - start) + "ms");
    // 等待接收关闭指令
    tomcat.getServer().await();
  }
}